package com.quasar.hpatient.module.home_event;

import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.quasar.hpatient.R;
import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.bean.home_inspection.InspectionBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.Observable;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelAcceptChangeListener;
import lib.quasar.context.BaseApp;
import lib.quasar.recycler.BaseCommonMultAdapter;
import lib.quasar.recycler.holder.RecyclerHolder;
import lib.quasar.recycler.manager.CrashLinearLayoutManager;
import lib.quasar.recycler.model.MultModel;
import lib.quasar.util.SpannableUtil;
import lib.quasar.widget.box.TextBox;
import lib.quasar.widget.group.RadioGroup;
import okhttp3.RequestBody;

/**
 * description: 首页 ==> 事件
 * created by kalu on 2018/4/25 22:23
 */
public class EventPresenter implements BasePresenter {

    private final LinkedList<InspectionBean.EventBean> mDatas = new LinkedList<>();

    final void initMenu(EventView view, TextView symptom, TextView length, TextView description) {

        SpannableUtil.append("不适症状", BaseApp.getColors(R.color.color_black));
        SpannableUtil.append(" (可多选)", BaseApp.getColors(R.color.color_bg_theme));
        view.setText(symptom, SpannableUtil.build());

        SpannableUtil.append("持续时间", BaseApp.getColors(R.color.color_black));
        SpannableUtil.append(" (单选)", BaseApp.getColors(R.color.color_bg_theme));
        view.setText(length, SpannableUtil.build());


        SpannableUtil.append("症状描述", BaseApp.getColors(R.color.color_black));
        SpannableUtil.append(" (选填)", BaseApp.getColors(R.color.color_bg_theme));
        view.setText(description, SpannableUtil.build());
    }

    final void initList(EventView view, RecyclerView recycler) {

        if (null == view || null == recycler) return;

        final BaseCommonMultAdapter<InspectionBean.EventBean> adapter = new BaseCommonMultAdapter<InspectionBean.EventBean>(mDatas) {

            @Override
            protected void onMult() {
                addMult(MultModel.TYPE_0, R.layout.activity_home_event_type_head);
                addMult(MultModel.TYPE_1, R.layout.activity_home_event_type_child);
            }

            @Override
            protected void onNext(RecyclerHolder holder, InspectionBean.EventBean model, int position) {

                if (model.getMultType() == MultModel.TYPE_0)
                    return;

                view.setText(holder, R.id.home_event_time, model.getTime());
                view.setText(holder, R.id.home_event_message, model.getEvent_name());
                view.setText(holder, R.id.home_event_length, model.getDay());
                view.setTextColor(holder, R.id.home_event_detail, model.getTextColor());

                holder.setOnClickListener(R.id.home_event_detail, v -> view.showDetail(position, model.getDescription()));
                holder.setOnClickListener(R.id.home_event_length, v -> view.showTime(position));
                holder.setOnLongClickListener(v -> {
                    view.showDelete(position, model.getEvent_name());
                    return true;
                }, R.id.home_event_time, R.id.home_event_message, R.id.home_event_length, R.id.home_event_detail);
            }
        };

        final CrashLinearLayoutManager manager = new CrashLinearLayoutManager(BaseApp.getContext());
        view.setRecycler(recycler, adapter, manager);
    }

    void eventList(EventView view, RecyclerView recycler, LinearLayout menu1, LinearLayout
            menu2, EditText menu3, String dateStr) {

        if (null == view || null == recycler || null == menu1 || null == menu2 || null == menu3)
            return;

        final String recordDate = TextUtils.isEmpty(dateStr) ? getDate() : getDate(dateStr);
        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.RECORD_DATE, recordDate);
        map.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_EVENT);

        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_3_2);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().listEvent(params);
        request(observable, new OnModelAcceptChangeListener<List<InspectionBean.EventBean>>() {
            @Override
            public void modelSucc(List<InspectionBean.EventBean> list) {

                if (null == list || list.isEmpty())
                    return;

                mDatas.clear();
                for (InspectionBean.EventBean model : list) {
                    if (model.isNull()) continue;
                    mDatas.addLast(model);
                }

                if (!mDatas.isEmpty()) {
                    mDatas.addFirst(new InspectionBean.EventBean());
                }
                view.refreshList(recycler);
            }

            @Override
            public void modelComplete() {
                switchMenu(menu1, menu2, menu3);
            }
        });
    }

    void saveEvent(EventView view, RecyclerView recycler, LinearLayout menu1, LinearLayout menu2, EditText menu3, RadioGroup group, EditText custom, String dateStr) {

        if (null == view || null == recycler || null == group || null == menu1 || null == menu2 || null == menu3)
            return;

        final String checkedText = group.getCheckedText();
        if (TextUtils.isEmpty(checkedText)) {
            view.toast("未选择持续时间");
            return;
        }

        final String length;
        if ("1天".equals(checkedText)) {
            length = "1";
        } else if ("2天".equals(checkedText)) {
            length = "2";
        } else if ("3天".equals(checkedText)) {
            length = "3";
        } else if ("4天".equals(checkedText)) {
            length = "4";
        } else if ("5天".equals(checkedText)) {
            length = "5";
        } else {
            length = "0";
        }

        final String recordDateTime = TextUtils.isEmpty(dateStr) ? getMinute() : getDateEvent(dateStr);

        boolean ok = false;
        String description = null;
        if (null != custom) {
            description = custom.getText().toString().trim();
        }

        LinkedList<InspectionBean.EventBean> pushList = new LinkedList<>();
        pushList.addAll(mDatas);
        if (!pushList.isEmpty()) {
            pushList.removeFirst();
        }

        for (int i = 0; i < menu1.getChildCount(); i++) {
            final TextBox box = (TextBox) menu1.getChildAt(i);
            if (!box.isChecked()) continue;
            ok = true;

            final String name = box.getText().toString().trim();
            if (TextUtils.isEmpty(name)) continue;

            final InspectionBean.EventBean model = new InspectionBean.EventBean();
            model.setEvent_name(name);
            model.setDuration_Length(length);
            model.setDescription(description);
            model.setEvent_datetime(recordDateTime);
            if (model.isTypeNull()) {
                model.setEvent_type(view.isSpecital() ? "1" : "2");
            }
            pushList.addFirst(model);
        }

        for (int i = 0; i < menu2.getChildCount(); i++) {
            final TextBox box = (TextBox) menu2.getChildAt(i);
            if (!box.isChecked()) continue;
            ok = true;

            final String name = box.getText().toString().trim();
            if (TextUtils.isEmpty(name)) continue;

            final InspectionBean.EventBean model = new InspectionBean.EventBean();
            model.setEvent_name(name);
            model.setDuration_Length(length);
            model.setDescription(description);
            model.setEvent_datetime(recordDateTime);
            if (model.isTypeNull()) {
                model.setEvent_type(view.isSpecital() ? "1" : "2");
            }
            pushList.addFirst(model);
        }

        final String name = menu3.getText().toString().trim();
        if (!TextUtils.isEmpty(name)) {
            ok = true;
            final InspectionBean.EventBean model = new InspectionBean.EventBean();
            model.setEvent_name(name);
            model.setDuration_Length(length);
            model.setDescription(description);
            model.setEvent_datetime(recordDateTime);
            if (model.isTypeNull()) {
                model.setEvent_type(view.isSpecital() ? "1" : "2");
            }
            pushList.addFirst(model);
        }

        if (!ok) {
            view.toast("未选择不适症状");
            return;
        }
        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_EVENT);
        map.put(HttpParams.DATAS, pushList);
        final String recordDate = TextUtils.isEmpty(dateStr) ? getDate() : getDate(dateStr);
        map.put(HttpParams.RECORD_DATE, recordDate);

        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_3_1);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().saveEvent(params);

        request(observable, new OnModelAcceptChangeListener<Object>() {
            @Override
            public void modelSucc(Object result) {

                mDatas.clear();
                mDatas.addFirst(new InspectionBean.EventBean());

                mDatas.addAll(pushList);
                view.refreshList(recycler);
                view.toast("保存成功");
            }

            @Override
            public void modelComplete() {
                custom.getText().clear();

                switchMenu(menu1, menu2, menu3);
            }
        });
    }

    void editEvent(EventView view, RecyclerView recycler, LinearLayout menu1, LinearLayout
            menu2, EditText menu3, String lengths, String message, String description, int position, String dateStr) {

        if (null == view || null == recycler || position >= mDatas.size())
            return;

        if (TextUtils.isEmpty(message) && TextUtils.isEmpty(lengths) && TextUtils.isEmpty(description))
            return;

        final InspectionBean.EventBean model = mDatas.get(position);

        if (!TextUtils.isEmpty(message)) {
            model.setEvent_name(message);
        }

        if (!TextUtils.isEmpty(description)) {
            model.setDescription(description);
        }
        if (lengths.length() == 2) {
            char[] chars = lengths.toCharArray();
            lengths = String.valueOf(chars[0]);
        } else if (lengths.length() > 2) {
            lengths = "0";
        }
        if (!TextUtils.isEmpty(lengths)) {
            if ("1".equals(lengths)) {
                model.setDuration_Length("1");
            } else if ("2".equals(lengths)) {
                model.setDuration_Length("2");
            } else if ("3".equals(lengths)) {
                model.setDuration_Length("3");
            } else if ("4".equals(lengths)) {
                model.setDuration_Length("4");
            } else if ("5".equals(lengths)) {
                model.setDuration_Length("5");
            } else {
                model.setDuration_Length("0");
            }
        }

        LinkedList<InspectionBean.EventBean> pushList = new LinkedList<>();
        pushList.addAll(mDatas);
        if (!pushList.isEmpty()) {
            pushList.removeFirst();
        }

        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_EVENT);
        map.put(HttpParams.DATAS, pushList);
        final String recordDate = TextUtils.isEmpty(dateStr) ? getDate() : getDate(dateStr);
        map.put(HttpParams.RECORD_DATE, recordDate);

        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_3_1);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().saveEvent(params);

        request(observable, new OnModelAcceptChangeListener<Object>() {

            @Override
            public void modelFail() {
                view.toast("修改失败");
            }

            @Override
            public void modelSucc(Object result) {
                view.refreshList(recycler);
                view.toast("修改成功");
            }

            @Override
            public void modelComplete() {
                switchMenu(menu1, menu2, menu3);
            }
        });
    }

    void deleteEvent(EventView view, RecyclerView recycler, int position, LinearLayout
            menu1, LinearLayout menu2, EditText menu3, String dateStr) {

        if (null == view || null == recycler || null == menu1 || null == menu2 || null == menu3)
            return;

        if (position >= mDatas.size()) return;
        final InspectionBean.EventBean old = mDatas.get(position);
        mDatas.remove(position);

        LinkedList<InspectionBean.EventBean> pushList = new LinkedList<>();
        pushList.addAll(mDatas);
        if (!pushList.isEmpty()) {
            pushList.removeFirst();
        }

        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_EVENT);
        final String recordDate = TextUtils.isEmpty(dateStr) ? getDate() : getDate(dateStr);
        map.put(HttpParams.RECORD_DATE, recordDate);
        map.put(HttpParams.DATAS, pushList);

        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_3_1);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().saveEvent(params);

        request(observable, new OnModelAcceptChangeListener<Object>() {

            @Override
            public void modelFail() {
                mDatas.add(position, old);
                view.toast("删除失败");
            }

            @Override
            public void modelSucc(Object result) {

                if (!mDatas.isEmpty() && mDatas.size() == 1) {
                    mDatas.clear();
                }

                view.refreshList(recycler);
                view.toast("删除成功");
            }

            @Override
            public void modelComplete() {
                switchMenu(menu1, menu2, menu3);
            }
        });
    }

    private final void switchMenu(LinearLayout menu1, LinearLayout menu2, EditText menu3) {
        if (null != menu3) {
            menu3.getText().clear();
        }

        if (null == menu1 || null == menu2) return;
        for (int i = 0; i < menu1.getChildCount(); i++) {
            final TextBox box = (TextBox) menu1.getChildAt(i);
            box.setClickable(true);
        }
        for (int i = 0; i < menu2.getChildCount(); i++) {
            final TextBox box = (TextBox) menu2.getChildAt(i);
            box.setClickable(true);
        }
        for (InspectionBean.EventBean model : mDatas) {
            final int position = model.getPosition();
            if (position == 8) continue;
            if (position <= 3) {
                final TextBox box = (TextBox) menu1.getChildAt(position);
                box.setClickable(false);
                box.setChecked(false);
            } else {
                final TextBox box = (TextBox) menu2.getChildAt(position - 4);
                box.setClickable(false);
                box.setChecked(false);
            }
        }
    }

    public ArrayList<InspectionBean.EventBean> getList() {
        final ArrayList<InspectionBean.EventBean> list = new ArrayList<>();
        list.addAll(mDatas);
        if (!list.isEmpty()) {
            list.remove(0);
        }
        return list;
    }

    @Override
    public void recycler() {
    }
}
